package hystrix;

import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.*;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HelloCommand extends HystrixCommand<String>{

    static int i = 0;
    private String url;

    private String remark;
    CloseableHttpClient httpClient;

    protected HelloCommand(String url,String remark) {
        //父类构造器，设置命令组的key，默认用来作为线程池的key
//        super(HystrixCommandGroupKey.Factory.asKey("HelloCommandGroup"));
        //针对此Command的配置
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("HelloCommandGroup"))
        .andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(500))
        .andCommandKey(HystrixCommandKey.Factory.asKey("HelloCommand"))
        .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("poolKey")));
        ConfigurationManager.getConfigInstance().setProperty(
                "hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds",3000
        );
        System.out.println("commandKey name is : " + this.getCommandKey().name());
        this.httpClient = HttpClients.createDefault();
        this.url = url;
        this.remark = remark;
        i++;
    }

    protected String run() throws Exception {
        HttpGet httpGet = new HttpGet(url);
        System.out.println(remark);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        String responseString = EntityUtils.toString(response.getEntity());
        System.out.println("在run方法中显示结果("+i+")：" + responseString);
        return responseString;
    }

    @Override
    protected String getFallback() {
        String s = "Hystrix的fall back机制启动，回滚开始";
        System.out.println(s);
        SubCommand subCommand = new SubCommand("subCommand",url);
        subCommand.execute();
        return s;

    }
}
